# _*_ encoding: utf-8 _*_
# B站UP主所有视频信息爬虫
import os
import json
import requests
import config as cfg

class VideoInfoSpider(object):
    api = "https://api.bilibili.com/x/space/arc/search"
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36"
    }
    def __init__(self, mid):
        self.mid = mid
        self.path = os.path.join(cfg.SAVE_TO_PATH, f"{self.mid}.json")


    def getVideoInfo(self) -> iter:
        '''发送请求'''
        page = 1
        while True:
            params = {
                "mid": self.mid,
                "ps": 30,
                "tid": 0,
                "pn": page, # 页数
                "keyword": "",
                "order": "pubdate",
                "jsonp": "jsonp"
            }

            respnse = requests.get(self.api, params=params, headers=self.headers)
            data = respnse.json().get("data").get("list").get("vlist")
            yield data
            if not data:
                break
            # 页数自增
            page += 1


    def save_to_pc(self) -> None:
        '''保存本地'''
        with open(self.path, "w") as fp:
            fp.write("[")
            for datas in self.getVideoInfo():
                if datas:
                    json.dump(datas,fp)
                    fp.write(",")
            fp.write("[]]")
        return


    def loop(self, trace=True) -> None:
        '''运行'''
        self.save_to_pc()
        if trace:
            print(f"UP主视频信息存储路径- <{self.path}>")
        return


if __name__ == "__main__":
    it = VideoInfoSpider("163637592").save_to_pc()